import http from '@/comm/http/network.js'
import store from '@/store/index.js'
let _ = require('lodash')

/**
 * 获取所有文章
 */
export function getAllArticle(page,perPage = 2) {
	return new Promise((resolve, reject) => {
		http.get(`/posts?page=${page}&per_page=${perPage}`).then(res => {
			let tags = store.getters.tagList
			let list = res.data
			list.forEach(item => {
				let tagList = item.tags
				if (tagList.length > 0) {
					for (let i = 0; i < tagList.length; i++) {
						let data = tags[_.findIndex(tags, {
							id: tagList[i]
						})]
						tagList[i] = !data ? '未分类' : data.name
					}
				}
			})
			resolve(res)
		}).catch(err => {
			reject(err)
		});
	})
}

/**
 * 获取文章详情
 * @param {Number} id
 */
export function getAllArticleDetail(id) {
	return new Promise((resolve, reject) => {
		http.get(`/posts/${id}`).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		});
	})
}

/**
 * 获取所有标签
 */
export function getAllTags() {
	return new Promise((resolve, reject) => {
		http.get('/tags?per_page=99&order=desc&orderby=count').then(res => {
			store.dispatch('app/setTagList', res.data)
			resolve(res)
		}).catch(err => {
			reject(err)
		});
	})
}

/**
 * 获取用户信息
 * @param {Object} id 用户id
 */
export function getAuthor(id) {
	return new Promise((resolve, reject) => {
		http.get(`/users/${id}`).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		});
	})
}

/**
 * 获取搜索
 * @param {Object} search 搜索关键字
 */
export function getSearch(search) {
	return new Promise((resolve, reject) => {
		http.get(`/search?search=${search}`).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		});
	})
}
